package com.hup.utils.commons;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hugan
 * @date 2019/8/9
 */
public abstract class CacheHandler<D> {

    public final int cacheSize;
    public final ArrayList<D> lstData;

    public CacheHandler() {
        this.cacheSize = 0;
        lstData = new ArrayList<>();
    }

    public CacheHandler(int cacheSize) {
        this.cacheSize = cacheSize;
        lstData = new ArrayList<>();
    }

    /**
     * @return 有没有触发处理数据
     */
    public boolean doAddData(D data) {
        lstData.add(data);
        if (isLimit()) {
            doHandleData();
            lstData.clear();
            return true;
        }
        return false;
    }

    /**
     * @return 有没有触发处理数据
     */
    public boolean doAddData(List<D> data) {
        lstData.addAll(data);
        if (isLimit()) {
            doHandleData();
            lstData.clear();
            return true;
        }
        return false;
    }

    public void doFinish() {
        doHandleData();
        lstData.clear();
    }

    /**
     * 可以重写
     * @return 默认>=cacheSize时触发doHandleData
     */
    public boolean isLimit() {
        return lstData.size() >= cacheSize;
    }

    public abstract void doHandleData();

}
